package com.secneo.appshare.activities;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.secneo.appshare.R;
import com.secneo.appshare.adapter.CommentListAdapter;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.Comment;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.ActivityUtil;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.Util;
import com.secneo.appshare.threads.GetAppCommentsThread;

public class ApplicationCommentsActivity extends Activity {

	private CommentListAdapter mAdapter = null;
	private ListView mCommentList = null;

	private String package_name;
	private int number;
	private String uid;
	private Boolean installed_not_addicted;
	private String app_name;
	private byte[] imageBytes;
	private String app_icon_url;

	private ProgressDialog mWaitDlg;

	private GetAppCommentsThread mGetAppCommentsThread;

	private EditText mCommentDataEt;
	private Button mCommentBtn;
	
	private TextView mEmptyText ;
	
	public static boolean mRecyleFlag = false ;

	private final int MSG_INIT_OK = 1;
	private final int MSG_INIT_ERROR = 2;
	private final int MSG_INIT_DROP = 3;
	private final int ADD_NEW_COMMENT = 4;

	private boolean isAlive = true;
	
	private int getCountInterval = 5 ;
	
	private String timeStamp = null ;	//分页使用
	private LinearLayout loadingLayout = null ;

	private ArrayList<Comment> commentList = new ArrayList<Comment>() ;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constants.MODE_GET_APP_COMMENTS_FINISH:
				if (mWaitDlg != null && mWaitDlg.isShowing()) {
					mWaitDlg.dismiss();
				}
				
				if (mAdapter == null && mGetAppCommentsThread.getCommentInfo().commentList != null &&  
						mGetAppCommentsThread.getCommentInfo().commentList
						.isEmpty()) {
					// empty
					mEmptyText.setVisibility(View.VISIBLE) ;
					if(loadingLayout != null){
						loadingLayout.removeAllViews() ;
					}
				} else if (mAdapter != null){
					//动态加载更多
					timeStamp = mGetAppCommentsThread.getCommentInfo().timeStamp ;
					int count = mGetAppCommentsThread.getCommentInfo()
							.commentList.size() ;
					for(int i = 0 ; i < count ; ++i){
						commentList.add(mGetAppCommentsThread.getCommentInfo().
								commentList.get(i)) ;
					}
					mAdapter.notifyDataSetChanged() ;
					
					if(count < getCountInterval){
						//加载完毕
						loadingLayout.removeAllViews() ;
					} else {
						loadingLayout.removeAllViews() ;
						loadingLayout.addView(loadMoreBtn) ;
					}
					
				} else {
					int count = mGetAppCommentsThread.getCommentInfo().commentList.size() ;
					for(int i = 0 ; i < count ; ++i){
						commentList.add(mGetAppCommentsThread.getCommentInfo().
								commentList.get(i)) ;
					}
					mAdapter = new CommentListAdapter(
							ApplicationCommentsActivity.this
									.getApplicationContext(), commentList, this);
					timeStamp = mGetAppCommentsThread.getCommentInfo().timeStamp ;
					mCommentList.setAdapter(mAdapter);
					
					if(count < getCountInterval){
						//加载完毕
//						loadingLayout.removeAllViews() ;
						mCommentList.removeFooterView(loadingLayout) ;
					}
					
					if(5 == getCountInterval){
						getCountInterval = 10 ;
					}
				}
				break;
			case Constants.MODE_GET_APP_COMMENTS_NET_ERROR:
				if (mWaitDlg != null && mWaitDlg.isShowing()) {
					mWaitDlg.dismiss();
				}
				showNetworkErrView() ;
				break;
			case Constants.MODE_GET_APP_COMMENTS_IMG_FINISH:
				if (mAdapter != null)
					mAdapter.notifyDataSetChanged();
				break;
			case Constants.MSG_GET_APP_COMMNETS_STATUS_ERROR:
				break;
			case Constants.MSG_GET_APP_COMMNETS_STATUS_OK:
				break;

			case MSG_INIT_OK: // 评论成功
				if (mWaitDlg != null && mWaitDlg.isShowing()) {
					mWaitDlg.dismiss();
					mWaitDlg = null;
				}
				ActivityUtil.showToast(ApplicationCommentsActivity.this,
						ApplicationCommentsActivity.this.getResources()
								.getText(R.string.pinglun_title).toString(),
						ApplicationCommentsActivity.this.getResources()
								.getText(R.string.pinglun_sucess).toString());

				{
					final String commentData = mCommentDataEt.getText().toString();
					mCommentDataEt.setText("") ;					
					Thread addNewCommentThead = new Thread() {
						public void run() {
							Comment comment = new Comment();
							comment.uid = LocalStore.getLocaleStoreInstance()
									.getUid();
							try {
								comment.user_icon_drawable = Util
										.getDrawableFromCache(
												ApplicationCommentsActivity.this,
												LocalStore
														.getLocaleStoreInstance()
														.getAvatarName());
							} catch (IOException e) {
								e.printStackTrace();
							}
							comment.comment = commentData ;
							comment.date = MessageFormat.format(
									"{0,date,yyyy年MM月dd日}",
									new Object[] { new java.sql.Date(System
											.currentTimeMillis()) });
							comment.uname = LocalStore.getLocaleStoreInstance()
									.getNickName();
//							
							commentList.add(0, comment) ;
							mEmptyText.setVisibility(View.GONE) ;
							if(mAdapter == null){
								mAdapter = new CommentListAdapter(
									ApplicationCommentsActivity.this
											.getApplicationContext(),
									mGetAppCommentsThread.getCommentInfo().commentList,
									mHandler);
							}
							if(isAlive)
								mHandler.sendEmptyMessage(ADD_NEW_COMMENT);
						}
					};
					addNewCommentThead.start();
				}

				break;
			case MSG_INIT_ERROR:
				if (mWaitDlg != null) {
					mWaitDlg.dismiss();
					mWaitDlg = null;
				}
				Toast.makeText(ApplicationCommentsActivity.this,
						R.string.word_remark_is_error, 2000).show();
				break;

			case Constants.MSG_ACTION_MSG_OK:
				if (mWaitDlg != null) {
					mWaitDlg.dismiss();
					mWaitDlg = null;
				}
				Toast.makeText(ApplicationCommentsActivity.this,
						R.string.msg_ok, 2000).show();
				break;
			case Constants.MSG_ACTION_MSG_ERROR:
				if (mWaitDlg != null) {
					mWaitDlg.dismiss();
					mWaitDlg = null;
				}
				Toast.makeText(ApplicationCommentsActivity.this,
						R.string.msg_error, 2000).show();
				break;
			case MSG_INIT_DROP:
				if (mWaitDlg != null) {
					mWaitDlg.dismiss();
					mWaitDlg = null;
				}
				Toast.makeText(ApplicationCommentsActivity.this,
						"今日频率太高，明天再试吧", 2000).show();
				break;
			case ADD_NEW_COMMENT:
				mAdapter.notifyDataSetChanged();
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.appshare_app_comments);

		parseIntent();

		mCommentDataEt = (EditText) findViewById(R.id.data_edit);
		mCommentBtn = (Button) findViewById(R.id.submit_btn);
		mCommentBtn.setOnClickListener(commentListener);
		
		mEmptyText = (TextView) findViewById(R.id.empty_tv) ;

		mCommentList = (ListView) findViewById(R.id.comment_list);
		mCommentList.setDivider(getResources().getDrawable(R.drawable.list_divider)) ;
		mCommentList.addFooterView(showLayout()) ;

		timeStamp = MessageFormat.format("{0,date,yyyy-MM-dd HH:mm:ss}" ,
                new Object[]  {
                    new java.sql.Date(System.currentTimeMillis())
                });
		mGetAppCommentsThread = new GetAppCommentsThread(this, mHandler,
				package_name, number, uid, installed_not_addicted, 
				getCountInterval, timeStamp);
		mGetAppCommentsThread.start();

		showDialog();

	}

	// 以下为分页显示代码
	private static LinearLayout searchLayout = null ;
	private static Button loadMoreBtn = null ;
	public LinearLayout showLayout()
	{
		searchLayout = new LinearLayout(this);
		searchLayout.setOrientation(LinearLayout.HORIZONTAL);

		ProgressBar progressBar = new ProgressBar(this);
		progressBar.setPadding(0, 0, 15, 0);
		progressBar.setIndeterminateDrawable(getResources().getDrawable(R.drawable.progress_medium));
		searchLayout.addView(progressBar, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

		TextView textView = new TextView(this);
		textView.setText("加载中...");
		textView.setGravity(Gravity.CENTER_VERTICAL);
		searchLayout.addView(textView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
		searchLayout.setGravity(Gravity.CENTER);
		
		loadMoreBtn = new Button(getApplicationContext()) ;
		loadMoreBtn.setBackgroundResource(R.drawable.style_loading_more_btn) ;
		loadMoreBtn.setText("显示更多") ;
		loadMoreBtn.setTextSize(15) ;
		
		loadMoreBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				loadingLayout.removeAllViews() ;
				loadingLayout.addView(searchLayout, new LinearLayout.LayoutParams(
						LinearLayout.LayoutParams.WRAP_CONTENT, 
						LinearLayout.LayoutParams.WRAP_CONTENT));
				
				mGetAppCommentsThread = new GetAppCommentsThread(
						ApplicationCommentsActivity.this, mHandler,
						package_name, number, uid, installed_not_addicted, 
						getCountInterval, timeStamp);
				mGetAppCommentsThread.start();
			}
		}) ;
		
		loadingLayout = new LinearLayout(this);
		loadingLayout.addView(loadMoreBtn, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT, 
				LinearLayout.LayoutParams.WRAP_CONTENT));
		loadingLayout.setGravity(Gravity.CENTER);
		return loadingLayout;
	}
	
	private void recycle(){
		if (mRecyleFlag) {
			// 回收资源
			mRecyleFlag = false ;
			mCommentList.setAdapter(null) ;
			if (mAdapter != null)
				mAdapter.freeDrawable();
			mAdapter = null ;
			commentList.clear() ;
			getCountInterval = 5 ;
			loadingLayout.removeAllViews() ;
			loadingLayout.addView(loadMoreBtn) ;
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		recycle() ;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mRecyleFlag = false ;
		mCommentList.setAdapter(null) ;
		if (mAdapter != null)
			mAdapter.freeDrawable();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		Boolean needInit = intent.getBooleanExtra("FromGroup", false);
		if (needInit) {
			timeStamp = MessageFormat.format("{0,date,yyyy-MM-dd HH:mm:ss}" ,
	                new Object[]  {
	                    new java.sql.Date(System.currentTimeMillis())
	                });
			mGetAppCommentsThread = new GetAppCommentsThread(this, mHandler,
					package_name, number, uid, installed_not_addicted, 
					getCountInterval, timeStamp);
			mGetAppCommentsThread.start();

			showDialog();
		}
		super.onNewIntent(intent);
	}
	
	private void showNetworkErrView() {
		View view = ApplicationCommentsActivity.this
				.findViewById(R.id.error_user);
		view.setVisibility(View.VISIBLE);
		loadingLayout.removeAllViews() ;
	}

	private void showDialog() {

		View view = ApplicationCommentsActivity.this
				.findViewById(R.id.error_user);
		view.setVisibility(View.GONE);

		mWaitDlg = new ProgressDialog(this);
		String msg = getResources().getString(R.string.txt_loading);
		mWaitDlg.setMessage(msg);
		mWaitDlg.setCancelable(true);
		mWaitDlg.show();
	}

	private void parseIntent() {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			package_name = bundle.getString("package_name");
			number = bundle.getInt("n", 20);
			uid = bundle.getString("uid");
			installed_not_addicted = bundle.getBoolean(
					"installed_not_addicted", true);
			app_name = bundle.getString("app_name");
			imageBytes = bundle.getByteArray("app_icon_array");
			app_icon_url = bundle.getString("app_icon");
		}
	}

	OnClickListener commentListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			String commentContent = mCommentDataEt.getText().toString().trim();
			if (commentContent.length() == 0) {
				Toast.makeText(
						ApplicationCommentsActivity.this
								.getApplicationContext(),
						R.string.word_remark_error, 2000).show();
			} else {
				String note = "发送评论中...";
				mWaitDlg = ProgressDialog.show(
						ApplicationCommentsActivity.this, null, note, true);
				Thread sendRemark = new Thread(new Runnable() {
					@Override
					public void run() {
						String remarkContent = mCommentDataEt.getText()
								.toString().trim();
						RemoteApiImpl rai = new RemoteApiImpl();
						String uid = LocalStore.getLocaleStoreInstance(
								ApplicationCommentsActivity.this
										.getApplicationContext()).getUid();

						JSONObject js = rai.getUserAction(
								ApplicationCommentsActivity.this
										.getApplicationContext(), uid,
								remarkContent, package_name, "3");
						String status = "";
						try {
							status = js.getString("status");
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						if (js != null) {
							if ("ok".equals(status)) {
								mHandler.sendEmptyMessage(MSG_INIT_OK);
							} else if ("drop".equals(status)) {
								mHandler.sendEmptyMessage(MSG_INIT_DROP);
							}
						} else
							mHandler.sendEmptyMessage(MSG_INIT_ERROR);

						ActivityUtil.shareToWeibo(
								ApplicationCommentsActivity.this
										.getApplicationContext(),
								Constants.UPLOAD_ACTION_TALK, app_name,
								remarkContent, imageBytes, null, app_icon_url,
								null, package_name);

						if (!Constants.SWITCH_SINA_CUSTOM) {
							if (imageBytes != null) {
								rai.share2QWeiboMsg(
										ApplicationCommentsActivity.this
												.getApplicationContext(),
										Constants.UPLOAD_ACTION_TALK, app_name
												+ ":" + remarkContent,
										imageBytes, null, null, package_name);
							} else {
								rai.share2QWeiboMsg(
										ApplicationCommentsActivity.this
												.getApplicationContext(),
										Constants.UPLOAD_ACTION_TALK, app_name
												+ ":" + remarkContent, null,
										null, package_name);
							}
						}

					}
				});
				sendRemark.start();
			}
		}
	};

	
	
}
